﻿using System.Security.Cryptography;
using Wx.Standard.Base;
using Wx.Standard.Common;
using Wx.Standard.Extend;
using Wx.Standard.IService;
using Wx.Standard.Model.App;

namespace Wx.Standard.Service
{
    public class App : IApp
    {
        WxApp wxApp;
        internal App(WxApp wxApp)
        {
            this.wxApp = wxApp;
        }
        private App() { }
        SmallApp_KeyInfo IApp.GetKey(string code)
        {
            var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={wxApp.appOption.smallapp_appid}&secret={wxApp.appOption.smallapp_secret}&js_code={code}&grant_type=authorization_code";
            var key = JsonHelper.jsonToModel<SmallApp_KeyInfo>(BaseClass.getFormWechatService(url));
            return key;
        }

        SmallApp_UserInfo IApp.GetUser(SmallApp_InfoData data, string session_key)
        {
            //签名验证
            var sign = StringEncyptionHelper.sha1(data.rawData + session_key);
            if (sign.ToLower() != data.signature.ToLower())
            {
                throw new WeChatError("签名验证不通过");
            }

            //解密开始
            try
            {
                var user = JsonHelper.jsonToModel<SmallApp_UserInfo>(StringEncyptionHelper.aesDecrypt(data.encryptedData, session_key, data.iv, CipherMode.CBC));
                //水印验证
                if (user.watermark.appid != wxApp.appOption.smallapp_appid)
                {
                    throw new WeChatError("水印验证不通过");
                }
                return user;
            }
            catch
            {

                throw new WeChatError("解密失败");
            }
        }
    }
}
